<template>
  <div class="address-edit-box">
    <nav-bar>
      <template v-slot:default>{{ title }}</template>
    </nav-bar>
    <van-address-edit
        class="edit"
        :area-list="areaList"
        :address-info="addressInfo"
        :show-delete="type === 'edit'"
        show-set-default
        show-search-result
        :search-result="searchResult"
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="onSave"
        @delete="onDelete"
    />
  </div>
</template>

<script>
import {computed, defineComponent, onMounted, reactive, toRefs} from 'vue'
import NavBar from "../../../components/common/navbar/NavBar";
import {tdist} from "../../../utils/address";
import {Toast} from "vant";
import {addAddress, delAddress, editAddress, getAddressDetail} from "../../../network/address";
import router from "../../../router";
import {useRoute} from "vue-router";

export default defineComponent({
  name: "AddressEdit",
  components: {
    NavBar
  },
  setup() {
    const route = useRoute();
    const entityData = reactive({
      areaList: {
        province_list: {},
        city_list: {},
        county_list: {}
      },
      searchResult: [],
      addressInfo: {},
      type: '',
      addressId: ''
    });
    onMounted(() => {
      // 接收路由参数
      const {type, addressId} = route.query;
      entityData.type = type;
      entityData.addressId = addressId;
      if (type === 'edit') {
        Toast('数据加载中...');
      }
      // 省市区列表构造
      let _provinceList = {};
      let _cityList = {};
      let _countyList = {};
      tdist.getLev1().forEach(p => {
        _provinceList[p.id] = p.text;
        tdist.getLev2(p.id).forEach(c => {
          _cityList[c.id] = c.text;
          tdist.getLev3(c.id).forEach(cc => {
            _countyList[cc.id] = cc.text;
          });
        });
      });
      // 给当前页面的数据模型赋值
      entityData.areaList.province_list = _provinceList;
      entityData.areaList.city_list = _cityList;
      entityData.areaList.county_list = _countyList;

      // 如果是编辑状态，则初始化编辑数据
      if (type === 'edit') {
        getAddressDetail(addressId).then(res => {
          let _areaCode = '';
          /*
        areaList 为对象结构，包含 province_list、city_list、county_list 三个 key。
        每项以地区码作为 key，省市区名字作为 value。
        地区码为 6 位数字，前两位代表省份，中间两位代表城市，后两位代表区县，以 0 补足 6 位。
        比如北京的地区码为 11，以 0 补足 6 位，为 110000
        */
          // 根据区县名称反推区域码（区域码）
          const province = tdist.getLev1();
          Object.entries(entityData.areaList.county_list).forEach(([id, text]) => {
            // 先找出当前对应的区
            if (text === res.county) {
              // 找到区对应的几个省份
              const provinceIndex = province.findIndex(item => item.id.substr(0, 2) === id.substr(0, 2))
              // 找到区对应的几个市区
              // eslint-disable-next-line no-unused-lets
              const cityItem = Object.entries(entityData.areaList.city_list).filter(([cityId, city]) => cityId.substr(0, 4) === id.substr(0, 4))[0]
              // 对比找到的省份和接口返回的省份是否相等，因为有一些区会重名
              if (province[provinceIndex].text === res.province && cityItem[1] === res.city) {
                _areaCode = id
              }
            }
          });
          /* 数据库返回的数据字段
        address: "莲塘路鹏基工业区"
        city: "深圳市"
        county: "罗湖区"
        created_at: "2021-05-26T07:55:08.000000Z"
        id: 925
        is_default: 0
        name: "李四"
        phone: "13578788787"
        province: "广东省"
        updated_at: "2021-05-26T07:55:08.000000Z"*/
          entityData.addressInfo = {
            id: res.id,//	每条地址的唯一标识	number | string
            name: res.name,	// 收货人姓名	string
            tel: res.phone,	// 收货人手机号	string
            province: res.province,	// 省份	string
            city: res.city,	// 城市	string
            county: res.county,	// 区县	string
            addressDetail: res.address,	// 详细地址	string
            areaCode: _areaCode,	// 地区编码，通过省市区选择获取（必填）	string
            isDefault: !!res.is_default	// 是否为默认地址	boolean
          }

        })
      }
    });
    // 计算属性设置页码标题
    const title = computed(() => {
      return entityData.type === 'add' ? '新增地址' : '编辑地址';
    });

    // 保存按钮事件
    const onSave = (content) => {
      // 构建参数
      const params = {
        id: content.id,
        name: content.name,
        address: content.addressDetail,
        phone: content.tel,
        province: content.province,
        city: content.city,
        county: content.county,
        is_default: content.isDefault ? 1 : 0
      }
      // 新增操作
      if (entityData.type === 'add') {
        addAddress(params).then(res => {
          if (res.status === 201) {
            Toast('保存成功！');
            setTimeout(() => {
              router.back();
            }, 1000)
          }
        });
      }
      // 编辑操作
      if (entityData.type === 'edit') {
        editAddress(entityData.addressId, params).then(res => {
          if (res.status === 204) {
            Toast('保存成功！');
            setTimeout(() => {
              router.back();
            }, 1000);
          }
        });
      }
    }
    const onDelete = () => {
      delAddress(entityData.addressId).then(res => {
        if (res.status === 204) {
          Toast('删除成功');
          router.back();
        }
      })
    }

    return {
      ...toRefs(entityData),
      onSave,
      onDelete,
      title
    }
  }
})
</script>

<style lang="scss">
.edit {
  .van-field__body {
    textarea {
      height: 26px !important;
    }
  }
}

.address-edit-box {
  margin-top: 44px;

  .van-address-edit {
    .van-button--danger {
      background: var(--color-tint);
      border-color: var(--color-tint);
    }

    .van-button--default {
      background: red;
      border-color: red;
      color: #ffffff;
    }
  }
}
</style>